// pages/publishOrder/publishOrder.js
var api = require('../../utils/networkApi.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    currentTab: 0, // tab切换 
    transportDirection: 0, //0 进口 1出口
    remarks: "请输入箱型箱量，运费等其他信息",
    chooseViewShowBanner: true,
    addImagesArr: [],
    newAddImagesArr: [],
    //提示弹出框是否显示
    showTipsDialog: false,
    //发单弹出框高度
    dialogHeight: "",
    //弹出框提示内容
    dialogContent: "",
    //弹窗左边按钮
    dialogLeftBtnText: "",
    //弹窗右边按钮
    dialogRightBtnText: "",
    //弹窗标识
    dialogType: "0", //0 发单 1 删除 2 申请撤销
    //弹出框弹出高度
    dialogBottomHeight: "",
    //弹出框标题颜色
    topTitleColor: "#192D69",
    //弹出框标题
    topTitle: "声明",
    //弹出框内容左边间距
    contentLeft: "35",
    //弹出框内容右边间距
    contentRight: "35",
    //弹出框内容高度
    contentHeight: "",
    //弹出框顶部标题是否显示
    isShowTitle: "0", // 0 显示  1  不显示
    //分页查询
    currentPage: 1,
    allPage: '',
    //待处理数据
    trustOrderListPageWp: [],
    //删除的position
    delPosition: 0,
    //要删除的item
    delItem: "",
    //删除的position
    revokePosition: 0,
    //要删除的item
    revokeItem: "",
    refreshing: false,
    nomore: false,
  },
  /** 
   * 点击tab切换 
   */
  swichNav: function(e) {

    var that = this;

    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },
  /** 
   * 滑动切换tab 
   */
  bindChange: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });

    //切换到待处理页面请求数据
    if (e.detail.current == 1) {
      this.setData({
        trustOrderListPageWp: [],
        allPage: "",
        currentPage: 1
      });
      this.getTrustOrderListPageWp();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  //页面滑动到底部
  loadMore: function() {

    this.setData({
      refreshing: true
    })
    if (this.data.currentPage >= this.data.allPage) {
      this.setData({
        refreshing: false,
        nomore: true,
      });
      return;
    } else {
      this.data.currentPage = this.data.currentPage + 1;
      this.getTrustOrderListPageWp();
    }
  },

  refresh: function() {

    this.setData({
      refreshing: true,
      trustOrderListPageWp: [],
      allPage: "",
      currentPage: 1
    })

    this.getTrustOrderListPageWp();
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //发布订单按钮
  publishClick: function() {


    if (this.data.addImagesArr.length == 0) {
      wx.showToast({
        title: '请上传单照',
        icon: 'none'
      })
      return;
    }
    for (var i = 0; i < this.data.addImagesArr.length; i++) {
      if (this.data.addImagesArr[i]['upload_percent'] < 100) {
        wx.showToast({
          title: '请等待片刻,第' +(i+1) + '张照片未上传完毕',
          icon: 'none'
        })
        return;
      }
    }

    if (this.data.remarks == "请输入箱型箱量，运费等其他信息") {
      wx.showToast({
        title: '请填写备注',
        icon: 'none'
      })
      return;
    }

    this.setData({
      dialogHeight: "629"
    })
    //计算弹出框弹出高度
    var bottomHeight = (app.globalData.screenHeight - this.data.dialogHeight) / 2

    this.setData({
      showTipsDialog: !this.data.showTipsDialog,
      dialogContent: "1、本小程序所有货运订单信息平台不做任何信息真实性担保。请用户进行自行核对信息的准确性。若出现虚假货运信息造成的损失平台不承担该损失。\n2、我们将在您的同意及确认下，通过注册表格等形式要求您提供一些个人资料，请您绝对放心，我们在未经您同意的情况下，绝对不会将您的任何资料以任何方式泄露给任何第三方。\n3、由于用户将个人密码告知他人或与他人共享注册帐户，由此导致的任何个人资料泄露，本小程序免责。\n4、任何由于黑客攻击、计算机病毒侵入或发作、因政府管制而造成的暂时性关闭等因素影响网络正常经营的不可抗力而造成的个人资料泄露、丢失、被盗用或被窜改等，本小程序均得免责。\n5、本小程序如因系统维护或升级而需暂停服务时，将提前1天公告。若因线路及非本公司控制范围外的硬件故障或其它不可抗力而导致暂停服务，于暂停服务期间造成的一切不便与损失，本小程序均得免责。\n6、凡以任何方式登陆本小程序或直接、间接使用本小程序资料者，视为自愿接受本小程序声明的约束。\n7、本声明未涉及的问题参见国家有关法律法规，当本声明与国家法律法规冲突时，以国家法律法规为准。",
      dialogLeftBtnText: "取消",
      dialogRightBtnText: "确认",
      dialogBottomHeight: bottomHeight,
      //弹出框内容左边间距
      contentLeft: "35",
      //弹出框内容右边间距
      contentRight: "35",
      //弹出框顶部标题是否显示
      isShowTitle: "0", // 0 显示  1  不显示
      dialogType: "0",
      contentHeight: "420"
    });

  },
  //点击进口
  selectedImport: function() {
    if (this.data.transportDirection == 0) {
      return false;
    } else {
      this.setData({
        transportDirection: 0,
      })
      this.data.transportDirection = 0;
    }
  },
  selectedExport: function() {
    if (this.data.transportDirection == 1) {
      return false;
    } else {
      this.setData({
        transportDirection: 1,
      })
      this.data.transportDirection = 1;
    }
  },
  chooseBanner: function(e) {
    var that = this;
    wx.chooseImage({
      count: 8 - that.data.addImagesArr.length,
      success: function(res) {
        var tempFiles = res.tempFiles;
        //将新选择的图片赋值给addimage数组
        for (var i = 0; i < tempFiles.length; i++) {
          tempFiles[i]['upload_percent'] = 0
          tempFiles[i]['path_server'] = ''
          that.data.addImagesArr.push(tempFiles[i]);
        }

        //判断是否隐藏选择图片
        that.chooseViewShowBanner();
        that.setData({
          addImagesArr: that.data.addImagesArr,
        });
        for (var i = 0; i < that.data.addImagesArr.length; i++) {
          if (that.data.addImagesArr[i]['upload_percent'] == 0) {
            that.uploadeImage(that, that.data.addImagesArr, i)
          }
        }

      }
    });
  },

  uploadeImage: function(that, upload_picture_list, i) {
    debugger
    var params = {
      'filePath': upload_picture_list[i]['path'],
      dataBody: {
        "file": 'file',
        "fileName": wx.getStorageSync('userToken'),
        "imgSource": 'bvatar'
      }
    }
    return new Promise((resolve, reject) => {
      var upload_task = wx.uploadFile({
        url: api.API_URL + '/imgproxy/zhys-img-service/img', // 仅为示例，非真实的接口地址
        filePath: params.filePath,
        name: 'file',
        formData: params.dataBody,
        success(res) {
          console.log(res)
          var obj = JSON.parse(res.data);
          debugger
          if (obj.code == 200 && obj.result.code == 0) {
            upload_picture_list[i]['path_server'] = obj.result.data.imagUrl
            that.setData({
              addImagesArr: upload_picture_list,
            });
          } else {
            wx.showToast({
              title: '图片上传失败，请重新登录',
              icon: 'none',
              duration: 3000
            })
          }

        },
        fail: function(e) {
          console.log(e)
        }
      })
      upload_task.onProgressUpdate((res) => {
        upload_picture_list[i]['upload_percent'] = res.progress
        that.setData({
          addImagesArr: upload_picture_list
        })
      })
    })
  },

  imageClick: function(e) {
    var that = this;
    var imageList = [];
    for (var i = 0; i < this.data.addImagesArr.length; i++) {
      imageList.push(this.data.addImagesArr[i].path)
    }
    wx.previewImage({
      current: that.data.addImagesArr[e.currentTarget.dataset.imageindex]['path'],
      urls: imageList,
    })
  },
  previewImg: function(event) {
    var that = this;
    var imgs = event.currentTarget.dataset.imgs;
    wx.previewImage({
      current: event.currentTarget.dataset.currentimg,
      urls: imgs,
    })
  },
  /** 删除图片Banner */
  deleteImvBanner: function(e) {
    var images = this.data.addImagesArr;
    var itemIndex = e.currentTarget.dataset.imageindex;
    images.splice(itemIndex, 1);
    this.setData({
      addImagesArr: images
    })
    //判断是否隐藏选择图片
    this.chooseViewShowBanner();
  },
  /** 是否隐藏图片选择Banner*/
  chooseViewShowBanner: function() {
    if (this.data.addImagesArr.length >= 8) {
      this.setData({
        chooseViewShowBanner: false
      })
    } else {
      this.setData({
        chooseViewShowBanner: true
      })
    }
  },
  /**
   *弹窗左边按钮 方法
   */
  dialogLeft() {
    if (this.data.showTipsDialog) {
      this.setData({
        dialogBottomHeight: 0,
      });
    }
    this.setData({
      showTipsDialog: !this.data.showTipsDialog
    });
  },
  /**
   *弹窗右边按钮 方法
   */
  dialogRight() {
    if (this.data.showTipsDialog) {
      this.setData({
        dialogBottomHeight: 0,
      });
    }
    //关闭弹窗
    this.setData({
      showTipsDialog: !this.data.showTipsDialog
    });
    if (this.data.dialogType == "0") {

      var imageList = [];
      for (var i = 0; i < this.data.addImagesArr.length; i++) {
        imageList.push(this.data.addImagesArr[i].path_server)
      }
      //确认发单
      var dataBody = {
        'type': this.data.transportDirection,
        'imageList': imageList,
        'remarks': this.data.remarks
      }
      api.networkForData("addTrustOrder", dataBody)
        .then(res => {
          this.setData({
            remarks: "请输入箱型箱量，运费等其他信息",
            chooseViewShowBanner: true,
            addImagesArr: [],
            transportDirection: 0
          })
          wx.navigateTo({
            url: '../publishSuccess/publishSuccess',
          })
        })
    } else if (this.data.dialogType == "1") {
      //删除
      var dataBody = {
        "trustOrderNo": this.data.delItem.trustOrderNo,
        "version": this.data.delItem.version
      }
      api.networkForData("delTrustOrderById", dataBody)
        .then(res => {
          this.data.trustOrderListPageWp.splice(this.data.delPosition, 1)
          this.setData({
            trustOrderListPageWp: this.data.trustOrderListPageWp
          })

        })
    } else if (this.data.dialogType == "2") {
      //申请撤销
      var dataBody = {
        "trustOrderNo": this.data.revokeItem.trustOrderNo,
        "version": this.data.revokeItem.version
      }
      api.networkForData("applyForTrustOrderBackById", dataBody)
        .then(res => {
          var delApply = 'trustOrderListPageWp[' + this.data.revokePosition + '].delApply';
          var version = 'trustOrderListPageWp[' + this.data.revokePosition + '].version';

          this.setData({
            [delApply]: 1,
            [version]: (this.data.trustOrderListPageWp[this.data.revokePosition].version + 1)
          })
          wx.navigateTo({
            url: '../orderManager/revokeSuccess/revokeSuccess',
          })

        })
    }

  },

  /**
   * 控制 pop 的打开关闭
   * 该方法作用有2:
   * 1：点击弹窗以外的位置可消失弹窗
   * 2：用到弹出或者关闭弹窗的业务逻辑时都可调用
   */
  toggleTipsDialog() {
    if (this.data.showTipsDialog) {
      this.setData({
        dialogBottomHeight: 0,
      });
    }
    this.setData({
      showTipsDialog: !this.data.showTipsDialog
    });

  },
  //获取待处理页面数据
  getTrustOrderListPageWp: function() {

    var dataBody = {
      "pageData": {
        "page": this.data.currentPage,
        "pageSize": 10
      }
    }
    api.networkForData("getTrustOrderListPageWp", dataBody)
      .then(res => {
        console.log(res)
        this.setData({
          refreshing: false,
          nomore: false,
        });
        this.setData({
          trustOrderListPageWp: this.data.trustOrderListPageWp.concat(res.list),
          allPage: res.totalPage
        });

      })
  },
  //删除待处理
  delBtnClick: function(event) {
    this.setData({
      delItem: event.currentTarget.dataset.item,
      delPosition: event.currentTarget.dataset.index
    })

    this.setData({
      dialogHeight: "260"
    })
    //计算弹出框弹出高度
    var bottomHeight = (app.globalData.screenHeight - this.data.dialogHeight) / 2

    this.setData({
      showTipsDialog: !this.data.showTipsDialog,
      dialogContent: "删除后，您的订单不会在列表出现",
      dialogLeftBtnText: "取消",
      dialogRightBtnText: "确认",
      dialogBottomHeight: bottomHeight,
      //弹出框内容左边间距
      contentLeft: "70",
      //弹出框内容右边间距
      contentRight: "70",
      //弹出框顶部标题是否显示
      isShowTitle: "1", // 0 显示  1  不显示
      dialogType: "1",
      contentHeight: "180"
    });
  },
  //申请撤销
  revokeClick: function(event) {
    this.setData({
      revokeItem: event.currentTarget.dataset.item,
      revokePosition: event.currentTarget.dataset.index
    })

    this.setData({
      dialogHeight: "260"
    })
    //计算弹出框弹出高度
    var bottomHeight = (app.globalData.screenHeight - this.data.dialogHeight) / 2

    this.setData({
      showTipsDialog: !this.data.showTipsDialog,
      dialogContent: "申请撤销后，运营会收到撤销通知处理 同意后订单会从列表删除",
      dialogLeftBtnText: "取消",
      dialogRightBtnText: "确认",
      dialogBottomHeight: bottomHeight,
      //弹出框内容左边间距
      contentLeft: "70",
      //弹出框内容右边间距
      contentRight: "70",
      //弹出框顶部标题是否显示
      isShowTitle: "1", // 0 显示  1  不显示
      dialogType: "2"
    });
  }
})